<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="800px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="loading"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="调度编号" prop="dispatchCode">
            <el-input v-model="formData.dispatchCode" placeholder="请输入调度编号" :disabled="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="水库名称" prop="reservoirName">
            <el-select v-model="formData.reservoirName" placeholder="请选择水库" :disabled="isView" style="width: 100%">
              <el-option label="东圳水库" value="东圳水库" />
              <el-option label="金钟水库" value="金钟水库" />
              <el-option label="西音水库" value="西音水库" />
              <el-option label="山美水库" value="山美水库" />
              <el-option label="惠女水库" value="惠女水库" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="调度类型" prop="dispatchType">
            <el-select v-model="formData.dispatchType" placeholder="请选择调度类型" :disabled="isView" style="width: 100%">
              <el-option label="防洪调度" value="flood-control" />
              <el-option label="供水调度" value="water-supply" />
              <el-option label="发电调度" value="power-generation" />
              <el-option label="生态调度" value="ecological" />
              <el-option label="应急调度" value="emergency" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="调度状态" prop="status">
            <el-select v-model="formData.status" placeholder="请选择状态" :disabled="isView" style="width: 100%">
              <el-option label="计划中" value="planned" />
              <el-option label="执行中" value="executing" />
              <el-option label="已完成" value="completed" />
              <el-option label="已暂停" value="paused" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="formData.startTime"
              type="datetime"
              placeholder="请选择开始时间"
              :disabled="isView"
              style="width: 100%"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="formData.endTime"
              type="datetime"
              placeholder="请选择结束时间"
              :disabled="isView"
              style="width: 100%"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="水位变化" prop="waterLevelChange">
            <el-input-number
              v-model="formData.waterLevelChange"
              placeholder="请输入水位变化"
              :disabled="isView"
              :precision="2"
              :step="0.1"
              style="width: 100%"
            />
            <span style="margin-left: 8px; color: #909399;">米</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="流量" prop="flow">
            <el-input-number
              v-model="formData.flow"
              placeholder="请输入流量"
              :disabled="isView"
              :precision="2"
              :step="1"
              :min="0"
              style="width: 100%"
            />
            <span style="margin-left: 8px; color: #909399;">m³/s</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="调度员" prop="dispatcher">
            <el-input v-model="formData.dispatcher" placeholder="请输入调度员姓名" :disabled="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="formData.phone" placeholder="请输入联系电话" :disabled="isView" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="调度级别" prop="level">
            <el-select v-model="formData.level" placeholder="请选择调度级别" :disabled="isView" style="width: 100%">
              <el-option label="一级" value="level1" />
              <el-option label="二级" value="level2" />
              <el-option label="三级" value="level3" />
              <el-option label="四级" value="level4" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="紧急程度" prop="urgency">
            <el-select v-model="formData.urgency" placeholder="请选择紧急程度" :disabled="isView" style="width: 100%">
              <el-option label="一般" value="normal" />
              <el-option label="紧急" value="urgent" />
              <el-option label="特急" value="critical" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="调度目的" prop="purpose">
        <el-input
          v-model="formData.purpose"
          type="textarea"
          :rows="3"
          placeholder="请输入调度目的"
          :disabled="isView"
        />
      </el-form-item>

      <el-form-item label="调度方案" prop="plan">
        <el-input
          v-model="formData.plan"
          type="textarea"
          :rows="3"
          placeholder="请输入调度方案"
          :disabled="isView"
        />
      </el-form-item>

      <el-form-item label="执行结果" prop="result">
        <el-input
          v-model="formData.result"
          type="textarea"
          :rows="3"
          placeholder="请输入执行结果"
          :disabled="isView"
        />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注信息"
          :disabled="isView"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button v-if="!isView" type="primary" @click="handleSubmit" :loading="loading">
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'

// Props
interface Props {
  modelValue: boolean
  title: string
  dispatchData?: any
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  title: '新增调度',
  dispatchData: null
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  success: []
}>()

// 模拟API接口
const saveDispatch = async (data: any) => {
  // 模拟保存
  return { code: 200, msg: '保存成功' }
}

const updateDispatch = async (data: any) => {
  // 模拟更新
  return { code: 200, msg: '更新成功' }
}

// 响应式数据
const loading = ref(false)
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive({
  id: null,
  dispatchCode: '',
  reservoirName: '',
  dispatchType: '',
  startTime: '',
  endTime: '',
  status: 'planned',
  waterLevelChange: 0,
  flow: 0,
  dispatcher: '',
  phone: '',
  level: '',
  urgency: 'normal',
  purpose: '',
  plan: '',
  result: '',
  remark: ''
})

// 表单验证规则
const formRules: FormRules = {
  dispatchCode: [
    { required: true, message: '请输入调度编号', trigger: 'blur' }
  ],
  reservoirName: [
    { required: true, message: '请选择水库名称', trigger: 'change' }
  ],
  dispatchType: [
    { required: true, message: '请选择调度类型', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择调度状态', trigger: 'change' }
  ],
  dispatcher: [
    { required: true, message: '请输入调度员姓名', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  purpose: [
    { required: true, message: '请输入调度目的', trigger: 'blur' }
  ]
}

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const isEdit = computed(() => props.dispatchData && props.dispatchData.id)
const isView = computed(() => props.title.includes('查看'))

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    dispatchCode: '',
    reservoirName: '',
    dispatchType: '',
    startTime: '',
    endTime: '',
    status: 'planned',
    waterLevelChange: 0,
    flow: 0,
    dispatcher: '',
    phone: '',
    level: '',
    urgency: 'normal',
    purpose: '',
    plan: '',
    result: '',
    remark: ''
  })
  
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 初始化表单数据
const initFormData = () => {
  if (props.dispatchData) {
    Object.assign(formData, props.dispatchData)
  } else {
    resetForm()
  }
}

// 监听弹窗显示
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      initFormData()
    }
  }
)

// 关闭弹窗
const handleClose = () => {
  visible.value = false
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    const submitData = { ...formData }
    
    if (isEdit.value) {
      await updateDispatch(submitData)
      ElMessage.success('更新成功')
    } else {
      await saveDispatch(submitData)
      ElMessage.success('保存成功')
    }

    emit('success')
  } catch (error) {
    console.error('提交失败:', error)
    if (error !== false) { // 排除表单验证失败的情况
      ElMessage.error('提交失败')
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input-number) {
  width: 100%;
}
</style>